﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;
using System.Linq;
using Kaio.Core;
using Kaio.Web.UI.Attributes;
using MvcForum.Net.Bussiness;

namespace MvcForum.Net.Controllers
{
    [ValidateIpAddress]
    [HandleError(View = "Error")]
    public class SearchController : BaseController
    {
        //
        // GET: /Search/


        private List<ForumUrl> Address
        {
            get
            {
                return new List<ForumUrl>
                           {
                               new ForumUrl
                                   {
                                       Title = ForumContext.GetText(LanguageSection.SEARCH,"PAGE_NAME"),
                                       Url = ForumContext.GetAbsoluteUrl(ForumUrls.SEARCH)
                                   }
                           };
            }
        }

        public ActionResult Index()
        {


            var _cmd = Request.QueryString["do"];

            if (!string.IsNullOrWhiteSpace(_cmd))
            {
                return Quick(null);
            }


            var _add = Address;

            ViewBag.NavAddress = _add;


            ViewBag.ActiveUrl = _add[0];


            #region List Forums

            /*  var _forums = ForumRepo.ListAll();

            var _f = new List<SelectListItem>
                         {
                             new SelectListItem
                                 {
                                     Text = ForumContext.GetText(LanguageSection.SEARCH, "ALL_FORUMS"),
                                     Value = "0"
                                 }
                         };
            _f.AddRange(from f in _forums
                        where ForumContext.ForumAllowAccess(f.AllowRoles)
                        select new SelectListItem
                                   {
                                       Text = string.Format("{0}{1}", ForumContext.Padding(f.Level), f.ForumName), Value = f.ForumId.ToString()
                                   });*/

            /*  _f.AddRange(_forums.Select(f => new SelectListItem
                                                {
                                                    Text = string.Format("{0}{1}", ForumContext.Padding(f.Level), f.ForumName),
                                                    Value = f.ForumId.ToString()
                                                }));*/


            /*  ViewBag.ForumList = _f;*/

            #endregion


            return View();
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidatePostback]
        public ActionResult Index(FormCollection form)
        {
            var _sqlScript = new StringBuilder();
            var _sqlWhere = new StringBuilder();

            string _keyword = form["_kwd"];

            var _msg = Msg.Create();

            _keyword = _keyword == "*" ? "" : _keyword.Replace("'", "''");


            if (_keyword.Length < 3)
            {
                _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, "ShortLength");

                return Json(_msg);
            }


            const string _kw = "@Kwd";


            _sqlScript.Append(ForumContext.Configuration.MaxSearchResults > 0
                                  ? String.Format("SELECT TOP {0}", ForumContext.Configuration.MaxSearchResults)
                                  : "SELECT");

            _sqlScript.AppendFormat(" T.*, F.ForumName FROM {0} INNER JOIN {1} ", "Topics T WITH(NOLOCK)",
                                    "Forums F WITH(NOLOCK)");
            _sqlScript.Append("ON T.ForumId=F.ForumId WHERE T.IsDeleted=0 AND T.IsApproved=1 AND");

            //Check Search Within
            int _temp = int.Parse(form["_searchwithin"]);

            switch (_temp)
            {
                case 0:
                    _sqlWhere.AppendFormat(" (T.TopicName LIKE N'%'+{0}+'%' OR T.Tags LIKE N'%'+{0}+'%'  OR  T.[Message] LIKE N'%'+{0}+'%')", _kw);
                    break;
                case 1:
                    _sqlWhere.AppendFormat(" (T.TopicName LIKE N'%'+{0}+'%')", _kw);

                    break;
                default:
                    _sqlWhere.AppendFormat(" (T.[Message] LIKE N'%'+{0}+'%')", _kw);
                    break;
            }


            //-----------Search Post With UserName

            var _u = form["_UserName"];

            if (!string.IsNullOrWhiteSpace(_u))
            {
                _sqlWhere.Append(" AND T.UserName ");
                _temp = int.Parse(form["_SearchKeywordType"]);

                _u = _u.Replace("'", "''");

                const string _user = "@Username";

                switch (_temp)
                {
                    case 0:
                        _sqlWhere.AppendFormat("LIKE N'%'+{0}+'%'", _user);
                        break;
                    case 1:
                        _sqlWhere.AppendFormat("LIKE N'+{0}+'%'", _user);
                        break;
                    case 2:
                        _sqlWhere.AppendFormat("LIKE N'%'+{0}+'", _user);
                        break;
                    default:
                        _sqlWhere.AppendFormat("={0}", _user);
                        break;
                }
            }

            //---------------------------

            _temp = int.Parse(form["_Replies"]);
            if (_temp > 0)
            {
                _sqlWhere.Append(" AND T.TotalReplies");

                _temp = int.Parse(form["_SearchPostsWith"]);
                _sqlWhere.AppendFormat(_temp == 0 ? ">={0}" : "<={0}", _temp);
            }

            //--------------------------

            _temp = int.Parse(form["_FindPostsFrom"]);

            if (_temp > 0)
            {
                _sqlWhere.Append(" AND T.Created");

                _sqlWhere.Append(_temp == 0 ? ">=" : "<=");

                _sqlWhere.AppendFormat("'{0}'", (DateTime.UtcNow - TimeSpan.FromDays(_temp)));
            }

            //------------------------

            var _f = form["_Forums"];

            if (_f != "0" && !string.IsNullOrWhiteSpace(_f))
            {
                bool _searchInSub;

                bool.TryParse(form["_issearchinsubforums"], out _searchInSub);

                /*if (_searchInSub)
                {

                    var _fIds = _f.Split();

                    var _forums = new List<int>();

                    foreach (string id in _fIds)
                    {
                        
                        var _subs = ForumRepo.Sub(int.Parse(id));

                        if (!_forums.Contains(int.Parse(id)))
                            _forums.Add(int.Parse(id));

                        foreach (Forum f in _subs)
                        {
                            if (ForumContext.ForumAllowAccess(f.AllowRoles))
                            {
                                if (!_forums.Contains(f.ForumId))
                                    _forums.Add(f.ForumId);
                            }
                        }
                    }

                    _f = string.Join(",", _forums.ToList());

                }*/


                _sqlWhere.AppendFormat(" AND T.ForumID IN ({0})", _f);
            }


            //Search Retult Type 
            //0: Topics
            //1: Posts
            _temp = int.Parse(form["_ShowResultsAs"]);

            if (_temp == 0)
            {
                var _sb = new StringBuilder(500);

                _sb.Append(" T.ReplyTo IS NULL AND T.TopicId IN");
                _sb.Append("(");

                _sb.Append("SELECT DISTINCT ISNULL(T.ReplyTo,T.TopicId) FROM ");
                _sb.Append("Topics T");
                _sb.Append(" WHERE ");
                _sb.Append(_sqlWhere);
                _sb.Append(")");
                _sqlScript.Append(_sb);
            }
            else
            {
                _sqlScript.Append(_sqlWhere);
            }


            //Sort Order 

            _sqlScript.Append(" ORDER BY ");

            _temp = int.Parse(form["_SortBy"]);

            switch (_temp)
            {
                case 1:
                    _sqlScript.Append("T.LastPosted");
                    break;
                case 2:
                    _sqlScript.Append("T.Created");
                    break;

                case 3:
                    _sqlScript.Append("T.Subject");
                    break;

                case 4:
                    _sqlScript.Append("T.TotalReplies");
                    break;

                case 5:
                    _sqlScript.Append("T.TotalViews");
                    break;
                default:
                    _sqlScript.Append("T.LastEdited");
                    break;
            }

            _sqlScript.Append(" " + form["_SortOrder"]);

            // _sqlScript.a

            /* var _sql =
                 "select T.*,F.ForumName from Topics T Inner JOIN Forums F ON T.ForumId=F.ForumId where T.TopicName like N'%'+@Kwd+'%' or T.[Message] like N'%'+@Kwd+'%'";*/



            /* try
             {*/
            var _data = TopicRepo.SearchAdvanced(_keyword, _u, _sqlScript.ToString());

            if (_data.Count > 0)
            {

                CacheHelper.Add(ForumContext.SessionID, _data, ForumContext.Configuration.SearchResultInCache);

                _msg.ReturnUrl = ForumContext.GetAbsoluteUrl(ForumUrls.SEARCH_RESULT, ForumContext.SessionID) + "?highlight=" + _keyword;

            }
            else
            {
                _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, Messages.SearchNoResults);
            }
            /*  }
              catch (Exception e)
              {

                  _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, Messages.SearchNoResults);

                 // _msg.Text = e.ToString()+"<br />"+ _sqlScript.ToString();
              }*/



            //_msg.Text = _sqlScript.ToString();

            return Json(_msg);


        }


        public ActionResult Quick(string id)
        {

            int _forumId;

            if (string.IsNullOrWhiteSpace(id))
                id = Request.QueryString["kwd"];

            int.TryParse(Request.QueryString["f"], out _forumId);

            var _isMod = ForumContext.IsSuperMod || ForumContext.IsModerated(_forumId);

            var _data = TopicRepo.QuickSearch(_forumId,_isMod, id, (short)SearchResultType.Thread, ForumContext.Configuration.MaxSearchResults);

            if (_data.Count > 0)
            {
                CacheHelper.Add(ForumContext.SessionID, _data, ForumContext.Configuration.SearchResultInCache);

                return Redirect(ForumContext.GetAbsoluteUrl(ForumUrls.SEARCH_RESULT, ForumContext.SessionID) + "?highlight=" + id);
            }


            ViewBag.NavAddress = Address;

            ViewBag.ActiveUrl = Address[0];

            ViewBag.Message = ForumContext.GetText(LanguageSection.MESSAGES, Messages.SearchNoResults);

            return View("Index");


        }


        public ActionResult Tag(string id)
        {

            return Quick(id);

            /* var _data = TopicRepo.QuickSearch(0, id, (short)SearchResultType.Thread, ForumContext.Configuration.MaxSearchResults);

            if (_data.Count > 0)
            {
                CacheHelper.Add(ForumContext.SessionID, _data, ForumContext.Configuration.SearchResultInCache);

                return Redirect(ForumContext.GetAbsoluteUrl(ForumUrls.SEARCH_RESULT, ForumContext.SessionID) + "?highlight=" + id);
            }

            ViewBag.Message = ForumContext.GetText(LanguageSection.MESSAGES, Messages.SearchNoResults);

            return View("Index");*/


        }

        public ActionResult Result(string id)
        {


            var _add = Address;

            var _url = new ForumUrl
            {
                Title = ForumContext.GetText(LanguageSection.SEARCH, "SEARCH_RESULT")

            };


            _add.Add(_url);

            ViewBag.ActiveUrl = _url;
            ViewBag.NavAddress = _add;

            var _data = CacheHelper.Get(id) as List<Topic>;



            if (_data != null && _data.Count > 0)
            {
                
                int _pageIndex;
                int _pageSize = ForumContext.Configuration.PageSize;

                int.TryParse(Request.QueryString["p"], out _pageIndex);

                if (_pageIndex == 0)
                    _pageIndex = 1;
                
                var p = string.Format("?highlight={0}&p={1}", Request.QueryString["highlight"], "{0}");

                var _topics = _data.Skip(_pageSize * (_pageIndex - 1)).Take(_pageSize).ToList();

                var _result = new ViewModelResult
                {
                    List = _topics,
                    Type = ResultType.Search,
                    
                    ButtonPageRenderPosition = (ButtonPageRenderPosition)ForumContext.Configuration.ButtonPageRenderPosition,
                    PageRender = ForumContext.PageRender(ForumContext.GetAbsoluteUrl(ForumUrls.SEARCH_RESULT, id) + p, _pageIndex, _pageSize, _data.Count)
                };


                return View(_result);
            }

            ViewBag.Message = ForumContext.GetText(LanguageSection.MESSAGES, Messages.SessionTimeout);

            return View("Index");


        }

        [ValidateAuthentication]
        public ActionResult GetNew()
        {

            var _date = DateTime.UtcNow.AddHours(-36);

            if (ForumContext.UserInfo.LastSearched.HasValue)
            {
                _date = ForumContext.UserInfo.LastSearched.Value;
            }

            var _data = TopicRepo.GetNewPosts((short)SearchResultType.Thread,ForumContext.Configuration.MaxSearchResults, _date);

            if (_data.Count > 0)
            {
                CacheHelper.Add(ForumContext.SessionID, _data, ForumContext.Configuration.SearchResultInCache);

                ForumContext.UserInfo.LastSearched = DateTime.UtcNow;

                return Redirect(ForumContext.GetAbsoluteUrl(ForumUrls.SEARCH_RESULT, ForumContext.SessionID));
            }

            ViewBag.NavAddress = Address;

            ViewBag.ActiveUrl = Address[0];

            ViewBag.Message = ForumContext.GetText(LanguageSection.MESSAGES, Messages.SearchNoResults);

            return View("Index");
        }


    }
}
